package com.cqeec.gams.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.cqeec.gams.entity.Account;
import com.cqeec.gams.entity.FunctionalModule;
import com.cqeec.gams.entity.Role;
import com.cqeec.gams.entity.RolePermission;
import com.cqeec.gams.model.Function;
import com.cqeec.gams.service.FunctionalModuleService;
import com.cqeec.gams.service.RoleService;

@Controller
@RequestMapping("/app/role/")
public class RoleController {
	@Autowired
	private RoleService roleService;
	@Autowired
	private FunctionalModuleService functionalModuleService;

	@RequestMapping("/delete/{page}/{size}/{id}")
	public String delete(@PathVariable int page, @PathVariable int size, @PathVariable String id) {
		roleService.delete(id);
		return "redirect:/app/role/index.html?page=" + page + "&size=" + size;
	}

	@RequestMapping("/index.html")
	public ModelAndView gotoListPage(String page, String size, String name) {
		ModelAndView mav = new ModelAndView("role/list");
		// List<Role> list = roleService.findAll();
		int pageNumber, pageSize;
		if (page == null || "".equals(page)) {
			pageNumber = 1;
		} else {
			pageNumber = Integer.parseInt(page);
		}
		if (size == null || "".equals(size)) {
			pageSize = 10;
		} else {
			pageSize = Integer.parseInt(size);
		}
//		List<Role> list;
//		long count;
//		if (name == null || "".equals(name)) {
//			// 调用不带查询条件的分页查询方法
//			count = roleService.countAll();
//			list = roleService.page(pageNumber, pageSize);
//		} else {
//			// 调用带查询条件的分页查询方法
//			count = roleService.countAllWithCondation(name);
//			list = roleService.page(pageNumber, pageSize, name);
//		}

		long count = roleService.count(name);
		long total = count % pageSize == 0 ? count / pageSize : count / pageSize + 1;
		if (total < pageNumber) {
			pageNumber = 1;
		}
		List<Role> list = roleService.page(pageNumber, pageSize, name);
		mav.addObject("count", count);
		mav.addObject("total", total);
		mav.addObject("page", pageNumber);
		mav.addObject("size", pageSize);
		mav.addObject("list", list);
		mav.addObject("name", name);
		return mav;
	}

	@RequestMapping("/add.html")
	public String gotoAddPage(Model model) {
		// 查询系统所有功能模块
		model.addAttribute("fmList", functionalModuleService.getAllFunction());
		return "role/add";
	}

	@RequestMapping("/update.html")
	public String update(Role role, Model model, HttpSession session) {
		// 难证数据
		// 保存数据到数据库
		try {
			Object obj = session.getAttribute("account");
			if (obj == null) {
				return "redirect:/login.html";
			} else {
				Account account = (Account) obj;
				role.setLastUpdater(account.getId());
				role.setLastUpdaterName(account.getName());
				role.setLastUpdateTime(new Date());
			}
			roleService.update(role);
			model.addAttribute("code", 0);
			model.addAttribute("message", "保存数据成功！");
		} catch (Exception ex) {
			ex.printStackTrace();
			model.addAttribute("role", role);
			model.addAttribute("code", 1);
			model.addAttribute("message", "保存数据失败！" + ex.getMessage());
		}
		return "role/edit";
	}

	@RequestMapping("/save.html")
	public String save(Role role, String[] function, Model model, HttpSession session) {
		// 验证数据
		// 保存数据到数据库
		List<String> roleHaveFunctionalModuleIdList = new ArrayList<String>();
		try {
			Object obj = session.getAttribute("account");
			if (obj == null) {
				return "redirect:/login.html";
			} else {
				Account account = (Account) obj;
				if (role.getId() == null) {
					role.setCreator(account.getId());
					role.setCreatorName(account.getName());
					role.setCreationTime(new Date());
				} else {
					role.setLastUpdater(account.getId());
					role.setLastUpdaterName(account.getName());
					role.setLastUpdateTime(new Date());
				}
			}
			roleService.save(role, function);
			model.addAttribute("code", 0);
			model.addAttribute("message", "保存数据成功！");
			// 获取角色拥有的功能模块
			List<RolePermission> roleHaveFunctionalModules = roleService.getRoleFunctionalModule(role.getId());
			for (RolePermission rp : roleHaveFunctionalModules) {
				roleHaveFunctionalModuleIdList.add(rp.getFunctionalModule());
			}
		} catch (Exception ex) {
			ex.printStackTrace();
			model.addAttribute("role", role);
			model.addAttribute("code", 1);
			model.addAttribute("message", "保存数据失败！" + ex.getMessage());
		}
		// 获取系统所有的功能模块
		List<Function> fmList = functionalModuleService.getAllFunction();
		for (Function f : fmList) {
			// 设置功能组
			if (roleHaveFunctionalModuleIdList.contains(f.getId())) {
				f.setSelected(true);
			}
			// 设置功能模块
			List<FunctionalModule> temp = f.getFunctionalModule();
			for (FunctionalModule fm : temp) {
				if (roleHaveFunctionalModuleIdList.contains(fm.getId())) {
					fm.setSelected(true);
				}
			}
		}
		model.addAttribute("fmList", fmList);
		return "role/add";
	}

	@RequestMapping("/edit/{id}")
	public ModelAndView gotoEditPage(@PathVariable String id) {
		ModelAndView mav = new ModelAndView("role/edit");
		Role role = roleService.get(id);
		mav.addObject("role", role);

		List<String> roleHaveFunctionalModuleIdList = new ArrayList<String>();
		// 获取角色拥有的功能模块
		List<RolePermission> roleHaveFunctionalModules = roleService.getRoleFunctionalModule(id);
		for (RolePermission rp : roleHaveFunctionalModules) {
			roleHaveFunctionalModuleIdList.add(rp.getFunctionalModule());
		}
		// 获取系统所有的功能模块
		List<Function> fmList = functionalModuleService.getAllFunction();
		for (Function f : fmList) {
			// 设置功能组
			if (roleHaveFunctionalModuleIdList.contains(f.getId())) {
				f.setSelected(true);
			}
			// 设置功能模块
			List<FunctionalModule> temp = f.getFunctionalModule();
			for (FunctionalModule fm : temp) {
				if (roleHaveFunctionalModuleIdList.contains(fm.getId())) {
					fm.setSelected(true);
				}
			}
		}
		mav.addObject("fmList", fmList);
		return mav;
	}
}
